package com.kapo.egroup.filter;

import cn.hutool.core.util.ObjectUtil;
import com.kapo.egroup.common.CacheConstants;
import com.kapo.egroup.config.RedisConfig;
import com.kapo.egroup.exception.CustomerAuthenticationException;
import com.kapo.egroup.security.handler.LoginFailureHandler;
import com.kapo.egroup.security.service.UserDetailsServiceImpl;
import com.kapo.egroup.utils.JwtUtils;
import com.kapo.egroup.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Title JwtAuthenticationTokenFilter
 * @Description TODO
 * @Author 86159
 * @Date 2022-10-16 02:46
 **/
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    RedisCache redisCache;

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    UserDetailsServiceImpl userDetailsService;

    @Autowired
    LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            //校验token
            String token = request.getHeader("Authentication");
            //若token为空，表示为匿名请求，直接通过，进入下一个filter
            if(ObjectUtil.isEmpty(token)){
                filterChain.doFilter(request,response);
                return;
            }
            //判断redis中是否存在该token(判断token是否过期)
            String tokenKey = CacheConstants.LOGIN_TOKEN_KEY + token;
            String redisToken = redisCache.get(tokenKey);
            if(ObjectUtil.isEmpty(redisToken)){
                throw new CustomerAuthenticationException("token不存在或已过期");
            }
            //如果token和Redis中的token不一致，则验证失败
            if(!token.equals(redisToken)){
                throw new CustomerAuthenticationException("token验证失败");
            }
            //如果存在token，则从token中解析出用户名（邮箱或手机号）
            String username = jwtUtils.getUsernameFromToken(token);

            //如果用户名为空，则解析失败
            if(ObjectUtil.isEmpty(username)){
                throw new CustomerAuthenticationException("token解析失败");
            }

            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (userDetails == null) {
                throw new CustomerAuthenticationException("token验证失败");
            }

            //创建身份验证对象
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

            //设置到Spring Security上下文
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        } catch (AuthenticationException e) {
            loginFailureHandler.onAuthenticationFailure(request,response,e);
        }
        filterChain.doFilter(request,response);
    }
}
